package com.zy.quartz.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zy.business.domain.TbProject;
import com.zy.business.mapper.ProjectMapper;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.utils.StringUtils;
import com.zy.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @description: 定时更新项目成员
 * @author: whf
 * @create: 2023-03-22 17:16
 **/
@Component("projectPersonTask")
public class ProjectPersonTask {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ISysUserService userService;

    //@Scheduled(cron="0 * * * * ?")
    public void updatePerson(){
        List<Map<String, Object>> mapList = projectMapper.selectMaps(new QueryWrapper<TbProject>().select("project_id as projectId","person_ids as personIds"));
        Map<String,Object> userMap = userService.getMap(new QueryWrapper<SysUser>().select("GROUP_CONCAT(user_id) as userId").ne("user_id", 1));
        String userIds = userMap.get("userId").toString();
        List<String> userIdList = Arrays.asList(userIds.split(","));
        //交集：list1.retainAll(list2); —>此时list1即为两个集合的交集
        //并集：list1.addAll(list2); —>此时list1即为两个集合的并集
        //差集：list1.removeAll(list2); —>此时list1即为两个集合的差集
        if (mapList!=null && mapList.size()>0){
            for (Map<String, Object> map : mapList) {
                String personIds = map.get("personIds").toString();
                List<String> personIdList = Arrays.asList(personIds.split(","));
                List<String> list1 = new ArrayList<String>();
                List<String> list2 = new ArrayList<String>();
                List<String> list3 = new ArrayList<String>();
                list1.addAll(personIdList);
                list2.addAll(personIdList);
                list3.addAll(personIdList);
                list1.retainAll(userIdList);
                list2.removeAll(list1);
                if (list2!=null && list2.size()>0) {
                    list3.removeAll(list2);
                    TbProject project = projectMapper.selectById(Long.valueOf(map.get("projectId").toString()));
                    project.setPersonIds(StringUtils.join(list3, ","));
                    projectMapper.updateTbProject(project);
                }
            }
        }
    }
}
